// information about server communication. This sample webservice is provided by Wikitude and returns random dummy places near given location
var ServerInformation = {
	POIDATA_SERVER: "http://location-wikitude.rhcloud.com/ws/points/",
	POIDATA_SERVER1: "http://location-wikitude.rhcloud.com/ws/points/type/10/",
	POIDATA_SERVER_ARG_LAT: "lat",
	POIDATA_SERVER_ARG_LON: "lon",
	POIDATA_SERVER_ARG_NR_POIS: "nrPois"
};

// implementation of AR-Experience (aka "World")
var World = {

	//loaded: false,
	//  user's latest known location, accessible via userLocation.latitude, userLocation.longitude, userLocation.altitude
	userLocation: null,

	// you may request new data from server periodically, however: in this sample data is only requested once
	isRequestingData: false,
	
	// if user click on a marker to find ways
	isFindWay: false,
	
	// if user input search bar
	isSearch: false,

	// true once data was fetched
	initiallyLoadedData: false,

	// different POI-Marker assets
	markerDrawable_idle: null,
	markerDrawable_selected: null,
	markerDrawable_directionIndicator: null,

	// list of AR.GeoObjects that are currently shown in the scene / World
	markerList: [],
	
	arrName : [],

	// The last selected marker
	currentMarker: null,
	
	currentStepMarker: null,
	
	// Save LatLng of selected marker
	selectedMarkerLat:0,
	selectedMarkerLng:0,
	
	// Save LatLng of user location when select a marker
	selUserLocationLat: 0,
	selUserLocationLng: 0,

	locationUpdateCounter: 0,
	updatePlacemarkDistancesEveryXLocationUpdates: 10,
	
	//Google map object
	map: null,
	
	// create maker from search
	
	// called to inject new POI data
	loadPoisFromJsonData: function loadPoisFromJsonDataFn(poiData) {

		// destroys all existing AR-Objects (markers & radar)
		AR.context.destroyAll();
		
		//Image Recognition
		World.createOverlays();
		
		//Google Map
		map = new googleMap();

		// show radar & set click-listener
		PoiRadar.show();
		$('#radarContainer').unbind('click');
		$("#radarContainer").click(PoiRadar.clickedRadar);

		// empty list of visible markers
		World.markerList = [];

		// start loading marker assets
		World.markerDrawable_idle = new AR.ImageResource("assets/marker_idle.png");
		World.markerDrawable_selected = new AR.ImageResource("assets/marker_selected.png");
		World.markerDrawable_directionIndicator = new AR.ImageResource("assets/indi.png");

		
			// loop through POI-information and create an AR.GeoObject (=Marker) per POI
			for (var currentPlaceNr = 0; currentPlaceNr < poiData.length; currentPlaceNr++) {
				var singlePoi = {
					"id": poiData[currentPlaceNr].id,
					"latitude": parseFloat(poiData[currentPlaceNr].latitude),
					"longitude": parseFloat(poiData[currentPlaceNr].longitude),
					"altitude": parseFloat(poiData[currentPlaceNr].altitude),
					"name": poiData[currentPlaceNr].name,
					"description": poiData[currentPlaceNr].description,
					"details": poiData[currentPlaceNr].details,
					"image": poiData[currentPlaceNr].image
				};

				World.markerList.push(new Marker(singlePoi));
			}
		
		

		// updates distance information of all placemarks
		World.updateDistanceToUserValues();

		World.updateStatusMessage(currentPlaceNr + ' places loaded');

		// set distance slider to 100%
		$("#panel-distance-range").val(100);
		$("#panel-distance-range").slider("refresh");
	},

	// sets/updates distances of all makers so they are available way faster than calling (time-consuming) distanceToUser() method all the time
	updateDistanceToUserValues: function updateDistanceToUserValuesFn() {
		for (var i = 0; i < World.markerList.length; i++) {
			World.markerList[i].distanceToUser = World.markerList[i].markerObject.locations[0].distanceToUser();
		}
	},

	// updates status message shon in small "i"-button aligned bottom center
	updateStatusMessage: function updateStatusMessageFn(message, isWarning) {

		var themeToUse = isWarning ? "e" : "c";
		var iconToUse = isWarning ? "alert" : "info";

		$("#status-message").html(message);
		$("#popupInfoButton").buttonMarkup({
			theme: themeToUse
		});
		$("#popupInfoButton").buttonMarkup({
			icon: iconToUse
		});
	},

	// location updates, fired every time you call architectView.setLocation() in native environment
	locationChanged: function locationChangedFn(lat, lon, alt, acc) {

		
		
		
		// store user's current location in World.userLocation, so you always know where user is
		World.userLocation = {
			'latitude': lat,
			'longitude': lon,
			'altitude': alt,
			'accuracy': acc
		};


		// request data if not already present
		if (!World.initiallyLoadedData) {
			World.requestDataFromServer();
			//World.loadPoisFromJsonData(myJsonData);
			//World.getDataFromServer();
			World.initiallyLoadedData = true;
		} else if (World.locationUpdateCounter === 0) {
			// update placemark distance information frequently, you max also update distances only every 10m with some more effort
			World.updateDistanceToUserValues();
		}

		// helper used to update placemark information every now and then (e.g. every 10 location upadtes fired)
		World.locationUpdateCounter = (++World.locationUpdateCounter % World.updatePlacemarkDistancesEveryXLocationUpdates);
		
		if(World.isFindWay ==true){
			World.findNextLocation();
		}
		
	},

	// fired when user pressed maker in cam
	onMarkerSelected: function onMarkerSelectedFn(marker) {
		
		//if(World.currentMarker!=null){
			//World.currentMarker.setDeselected(World.currentMarker);
		//}
		World.currentMarker = marker;
		$("#popup-poidetail").popup("open");

		// update panel values
		$("#poi-name").html(marker.poiData.name);
		$("#poi-description").html(marker.poiData.description);

		var distanceToUserValue = (marker.distanceToUser > 999) ? ((marker.distanceToUser / 1000).toFixed(2) + " km") : (Math.round(marker.distanceToUser) + " m");

		$("#poi-distance").html(distanceToUserValue);
		$("#poi-detail-distance").html(distanceToUserValue);
		$("#poi-detail-name").html(marker.poiData.name);
		$("#poi-detail-description").html(marker.poiData.description);
		$("#poi-detail-infomation").html(marker.poiData.details);
		$("#poi-detail-image").html(marker.poiData.image);

		//World.findFirstLocation();
		
		
		
	},

	// screen was clicked but no geo-object was hit
	onScreenClick: function onScreenClickFn() {
		// you may handle clicks on empty AR space too
	},

	// returns distance in meters of placemark with maxdistance * 1.1
	getMaxDistance: function getMaxDistanceFn() {

		// sort palces by distance so the first entry is the one with the maximum distance
		World.markerList.sort(World.sortByDistanceSortingDescending);

		// use distanceToUser to get max-distance
		var maxDistanceMeters = World.markerList[0].distanceToUser;

		// return maximum distance times some factor >1.0 so ther is some room left and small movements of user don't cause places far away to disappear
		return maxDistanceMeters * 1.1;
		
	},

	// reload places from content source
	reloadPlaces: function reloadPlacesFn() {
		World.isFindWay = false;
		if (!World.isRequestingData) {
			if (World.userLocation) {
				World.requestDataFromServer();
				//World.loadPoisFromJsonData(myJsonData);
				//World.getDataFromServer();
			} else {
				World.updateStatusMessage('Unknown user-location.', true);
			}
		} else {
			World.updateStatusMessage('Already requesing places...', true);
		}
	},
	
	// request POI data
	requestDataFromServer: function requestDataFromServerFn() {

		// set helper var to avoid requesting places while loading
		World.isRequestingData = true;
		World.updateStatusMessage('Requesting places from web-service');

		// server-url to JSON content provider
		var serverUrl = ServerInformation.POIDATA_SERVER;

		var jqxhr = $.getJSON(serverUrl, function(data) {
			World.loadPoisFromJsonData(data);
		})
			.error(function(err) {
				World.updateStatusMessage("Invalid web-service response.", true);
				World.isRequestingData = false;
			})
			.complete(function() {
				World.isRequestingData = false;
			});
	},

	// helper to sort places by distance
	sortByDistanceSorting: function(a, b) {
		return a.distanceToUser - b.distanceToUser;
	},

	// helper to sort places by distance, descending
	sortByDistanceSortingDescending: function(a, b) {
		return b.distanceToUser - a.distanceToUser;
		
	},
	
	getListName : function getListNameFn(list) {
		for (var i = 0; i < list.length; i++) {
			var singlePoi = {
				"id" : list[i].id,
				"name" : list[i].name,
				"latitude": parseFloat(list[i].latitude),
				"longitude": parseFloat(list[i].longitude),
				"altitude": parseFloat(list[i].altitude),
				"description": list[i].description,
				"details": list[i].details,
				"image": list[i].image		
			};
			World.arrName.push(singlePoi);
		}
	},
	
	createOverlays: function createOverlaysFn() {
		var arrString = ["pageOne", "pageTwo"];
		var arr = [];
		var arrPage = [];
		// initialize place
		var jqxhr = $.getJSON(ServerInformation.POIDATA_SERVER1, function(data) {
			for (var i = 0; i < data.length; i++) {
			var singlePoi = {
				"id" : data[i].id,
				"name" : data[i].name,
				"latitude": parseFloat(data[i].latitude),
				"longitude": parseFloat(data[i].longitude),
				"altitude": parseFloat(data[i].altitude),
				"description": data[i].description,
				"details": data[i].details,
				"image": data[i].image		
			};
			arr.push(singlePoi);
		}
		}).error(function(err) {
				World.updateStatusMessage("Invalid web-service response.", true);
				World.isRequestingData = false;
			})
			.complete(function() {
				World.isRequestingData = false;
			});
		
		// Initialize Tracker
		tracker = new AR.Tracker("assets/magazine.wtc", {
			onLoaded: this.worldLoaded
		});
		// Create overlay for page one
		var img = new AR.ImageResource("assets/marker_idle.png");
		var imgDraw1 = new AR.ImageDrawable(img, 0.1, {});
		var imgDraw = new AR.ImageDrawable(img, 0.1, {
			onClick: function(){
					$("#popup-poidetail").popup("open");
					$("#poi-name").html("abc");
					$("#poi-description").html(page.targetName);
			}
		});
		//for (var j = 0; j<arrString.length ; j++)
		//{
		var page = new AR.Trackable2DObject(tracker, arrString[0], {
		});
		//arrPage.push(page);
		//}
		
		page.addCamDrawable(imgDraw); // them dc
		
	},
	
	
	createWwwButton: function createWwwButtonFn(image, url, size, options) {
		options.onClick= function() {
			AR.context.openInBrowser(url);
		};
		return new AR.ImageDrawable(image, size, options);
	},

	worldLoaded: function worldLoadedFn() {
		
		Connect.insert();
		var cssDivLeft = " style='display: table-cell;vertical-align: middle; text-align: right; width: 50%; padding-right: 15px;'";
		var cssDivRight = " style='display: table-cell;vertical-align: middle; text-align: left;'";
		document.getElementById('loadingMessage').innerHTML =
		"<div" + cssDivLeft + ">Scan Target &#35;1 (surfer):</div>" +
			"<div" + cssDivRight + "><img src='assets/surfer.png'></img></div>";
	}
};


/* forward locationChanges to custom function */
AR.context.onLocationChanged = World.locationChanged;

/* forward clicks in empty area to World */
AR.context.onScreenClick = World.onScreenClick;




